const chalk = require('chalk')
const fse = require('fs-extra')
const path = require('path')
const inquirer = require('inquirer')

const { SupportedEditor, SupportedLanguage, SupportedStyleSheets, SupportedFramework } = require('./consts')

const { apply: applyEditor } = require('./editor')
const { apply: applyPkg } = require('./pkg')
const { apply: applyPrettier } = require('./prettier')
const { apply: applyLint } = require('./lint')
const { apply: applyDeps } = require('./deps')

module.exports = {
	run: async () => {
		const pkgFile = path.resolve(process.cwd(), './package.json')

		// 必须在一个npm项目下执行
		if (!fse.existsSync(pkgFile)) {
			console.log(chalk.red('请在工程目录下执行命令'))
			return
		}

		// 检测editorconfig配置，提示用户是否删除
		const editorConfigPath = path.resolve(process.cwd(), '.editorconfig')
		if (fse.existsSync(editorConfigPath)) {
			const res = await inquirer.prompt([
				{
					type: 'confirm',
					name: 'remove',
					message: '检测到.editorconfig文件，这将影响到对编辑器的设置，是否删除:',
					default: false
				}
			])

			if (res.remove) {
				fse.removeSync(editorConfigPath)
			}
		}

		const options = await inquirer.prompt([
			{
				type: 'list',
				name: 'editor',
				message: '请选择使用的编辑器:',
				choices: () => {
					return Object.entries(SupportedEditor).map(([key, value]) => ({
						name: key,
						value: value
					}))
				}
			},
			{
				type: 'list',
				name: 'language',
				message: '请选择编程语音:',
				choices: () => {
					return Object.entries(SupportedLanguage).map(([key, value]) => ({
						name: key,
						value: value
					}))
				}
			},
			{
				type: 'list',
				name: 'styleSheets',
				message: '请选择样式语言:',
				choices: () => {
					return Object.entries(SupportedStyleSheets).map(([key, value]) => ({
						name: key,
						value: value
					}))
				}
			},
			{
				type: 'list',
				name: 'framework',
				message: '请选择编程框架:',
				choices: () => {
					return Object.entries(SupportedFramework).map(([key, value]) => ({
						name: key,
						value: value
					}))
				}
			},
			{
				type: 'confirm',
				name: 'includeHtml',
				message: '是否包含html:',
				default: true
			}
		])

		// 应用编辑器配置
		try {
			applyEditor(options)
		} catch (error) {
			console.log(chalk.red('编辑器配置生成失败:'), error)
		}

		// 应用 package.json 配置
		try {
			applyPkg(options)
		} catch (error) {
			console.log(chalk.red('package.json配置生成失败:'), error)
		}

		// 应用 prettier 配置
		try {
			applyPrettier(options)
		} catch (error) {
			console.log(chalk.red('Prettier配置生成失败:'), error)
		}

		// 应用 lint 配置
		try {
			applyLint(options)
		} catch (error) {
			console.log(chalk.red(error))
		}

		// 安装相关依赖
		try {
			applyDeps(options)
		} catch (error) {
			console.log(chalk.red('依赖安装失败:'), error)
		}
	}
}
